import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)


const store = new Vuex.Store({
  state: {
    //获取并尝试使用本地储存的token
    token: localStorage.getItem("token") || '',
    info: localStorage.getItem("userInfo") || '',
    menuCollapse: false
  },
  //设置状态
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    REMOVE_TOKEN: (state) => {
      state.token = ''
    },
    //用户信息
    SAVE_USER: (state, res) => {
      state.info = res
    },
    REMOVE_USER: (state) => {
      state.info = ''
    },
    //菜单折叠
    SET_COLLAPSE: (state) => {
      state.menuCollapse = !state.menuCollapse
    }
  },
  //异步
  actions: {
    //登录--{commit}解构赋值
    login: ({ commit }, param) => {
      commit('SET_TOKEN', param)
      localStorage.setItem("token", param);
    },
    //退出登录
    logout: ({ commit }) => {
      commit('REMOVE_TOKEN')
      commit('REMOVE_USER')
      localStorage.removeItem("token")
      localStorage.removeItem("userInfo")
    },
    //用户信息
    userInfo: ({ commit }, param) => {
      commit('SAVE_USER', JSON.stringify(param))
      localStorage.setItem("userInfo", JSON.stringify(param))
    }
  }
})

export default store